// pages/chatlist/chatlist.js
const db = wx.cloud.database();
const _=db.command;
var app=getApp();
var y=app.globalData.y;
Page({

  /**
   * 页面的初始数据
   */
  data: {
      friendes:[],
  },


  onLoad: function (options) {
       //获取联系人列表
     
  },
  tabSelect:function(e){
    var current = e.currentTarget.dataset.id
    this.setData({
      current:current
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var flag = wx.getStorageSync('userFlag').flag; 
        if(flag==0) {
            wx.showModal({
                title: '提示',
                content: '你还未完善个人信息，是否立刻去完善？',
                success (res) {
                    if (res.confirm) {
                        wx.switchTab({
                            url: '/pages/user/index',
                        })
                    } else if (res.cancel) {
                                wx.switchTab({
                                    url: '/pages/index/index',
                                })
                            }
                    }
            })
        }
       
     if(y>0)
     {
         wx.showTabBarRedDot({
           index: 2,
         })
     }
     else{
         wx.hideTabBarRedDot({
           index: 2,
         })
     }
  var that = this;
       var user = wx.getStorageSync('userFlag')
            
       if(user.flag == 1){
           db.collection("chatlist").where({
               _id:db.RegExp({
                   regexp:'^.*'+user.user._id,
               })
           }).get().then(res=>{
              
               var friendes=[];
               for(var i =0;i<res.data.length;i++){
                    var friend = res.data[i].user1._id==user.user._id ? res.data[i].user2:res.data[i].user1;
                    var chat = res.data[i].chat;
                    var state=false;
                    var b=res.data[i].chat.length;
            
                    if(b>0&&!res.data[i].chat[b-1].state&&res.data[i].chat[b-1].sendid!=user.user._id)
                    {
                        state=true;
                         y++;
                    }

                    friendes.push({friend,chat,state})
               }
               app.globalData.y=y;

                that.setData({
                    friendes:friendes
                })

           })
       }
  },

  cancel(e){
  const{friendes} = this.data;
  
   if(friendes[e.currentTarget.dataset.id].state)
   {
      y--;
      y=y>0?y:0;
   }
   app.globalData.y=y;

   friendes[e.currentTarget.dataset.id].state=false;
   this.setData({
       friendes:friendes
   })

  },
  onPullDownRefresh:function () {
    setTimeout(()=>{ wx.stopPullDownRefresh({
    success: (res) => {}})},1000)  
}


})